package com.watchmen.wechat.news;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.collect.Maps;
import com.watchmen.wechat.config.WeChatConfig;
import com.watchmen.wechat.domain.WechatTemplateMsg;
import com.watchmen.wechat.token.WechatVoucher;
import com.watchmen.wechat.util.HttpRequest;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author kk
 * @Description 模板消息推送
 */
@Slf4j
@Component
public class TemplateMessage {

	
	@Autowired
	WeChatConfig weChatConfig;
	
	@Autowired
	WechatVoucher wechatVoucher;
	
	@Autowired
	HttpRequest httpRequest;
	
	
	/**
	 * 用于群发消息
	 * @param params  根据具体模板参数组装
	 * @param openIdList 微信Openid
	 * @param url 跳转的url
	 * @return 
	 * @throws Exception
	 */
	public String sendOut(TreeMap<String,TreeMap<String,String>> params,
			              List<String> openIdList,
			              String url) throws Exception {
		String industry = "";
		
		// 获取openid
		for (int i = 0; i < openIdList.size(); i++) {
			WechatTemplateMsg wechatTemplateMsg = new WechatTemplateMsg();
			
			String openId = openIdList.get(i);
			
			wechatTemplateMsg.setTouser(openId);
			wechatTemplateMsg.setUrl(url);
			wechatTemplateMsg.setTemplateId(weChatConfig.getTemplateId());  
			wechatTemplateMsg.setData(params);
			
			// 推送消息
			industry = this.getIndustry(wechatTemplateMsg);
		}
		return industry;
	}
	
	
	
	/**
	 * @param msg   消息内容
	 * @return 
	 * @throws Exception
	 */
	public String getIndustry(WechatTemplateMsg msg) throws Exception{
		
		log.info("推送消息{}",msg);
		
		String token = "";
		
		try {
			token = wechatVoucher.caches.get("access_token");
			// 获取access_token,没有则重新请求获取
			token =WechatVoucher.caches.get("access_token");
		} catch (Exception e) {
			try {
				// 重新请求获取
				wechatVoucher.voucher();
				token =wechatVoucher.caches.get("access_token");
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		
	
		log.info("token:"+token);
		
		// 推送消息
		String industryUrl = weChatConfig.getIndustryUrl().replace("TOKEN", token);
		
		String objJsonObject = JSONUtil.toJsonStr(msg);
		
		log.info("构造的json:{}",objJsonObject);
		
		String industry = httpRequest.doHttpsJson_HttpClient(industryUrl, "POST", objJsonObject);
		
		JSONObject parseObj = JSONUtil.parseObj(industry);
		
		String errmsg = parseObj.getStr("errmsg");
		
		
		
		if(errmsg.contains("ok")){
			log.info("微信返回........................"+errmsg);
			log.info("发送成功........................");
		}
		
		
		System.out.println(industry);
		
		return industry;
	}
	
	
}
